<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫描件PDF合并工具</title>
    <script src="https://unpkg.com/pdf-lib@1.17.1"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f7fa;
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            margin-bottom: 10px;
            font-size: 2.2rem;
        }
        
        .description {
            font-size: 1.1rem;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .upload-section {
            flex: 1;
            min-width: 300px;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        h2 {
            margin-bottom: 20px;
            color: #2c3e50;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        
        .drop-area {
            border: 2px dashed #3498db;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s;
            background-color: #f8fafc;
        }
        
        .drop-area:hover {
            background-color: #e1f0fa;
            border-color: #2980b9;
        }
        
        .drop-area p {
            margin-top: 10px;
            color: #7f8c8d;
        }
        
        .file-input {
            display: none;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: background-color 0.3s;
            text-align: center;
            margin-top: 10px;
        }
        
        .btn:hover {
            background-color: #2980b9;
        }
        
        .btn-merge {
            background-color: #2ecc71;
            width: 100%;
            padding: 15px;
            font-size: 18px;
            margin-top: 20px;
        }
        
        .btn-merge:hover {
            background-color: #27ae60;
        }
        
        .btn:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        
        .result-section {
            flex: 1;
            min-width: 300px;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            background-color: #f8f9fa;
            border-left: 4px solid #3498db;
        }
        
        .status.success {
            border-left-color: #2ecc71;
            background-color: #eafaf1;
        }
        
        .status.error {
            border-left-color: #e74c3c;
            background-color: #fdedec;
        }
        
        .visualization {
            margin-top: 30px;
            padding: 20px;
            background-color: #f8fafc;
            border-radius: 8px;
        }
        
        .page-sequence {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 15px 0;
            justify-content: center;
        }
        
        .page {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 5px;
            font-weight: bold;
        }
        
        .page-front {
            background-color: #3498db;
            color: white;
        }
        
        .page-back {
            background-color: #2ecc71;
            color: white;
        }
        
        .page-merged {
            background-color: #9b59b6;
            color: white;
        }
        
        footer {
            text-align: center;
            margin-top: 40px;
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>扫描件PDF合并工具</h1>
        <p class="description">解决【正面顺序，反面逆序】的PDF扫描件合并问题，将两个PDF文件交叉合并为正确的页码顺序</p>
    </header>
    
    <div class="container">
        <div class="upload-section">
            <h2>上传PDF文件</h2>
            
            <div class="drop-area" id="dropFront">
                <div>
                    <svg width="50" height="50" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M14 2H6C4.9 2 4.01 2.9 4.01 4L4 20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#3498db"/>
                        <path d="M14 2V8H20" fill="#2980b9"/>
                        <path d="M16 13H8V11H16V13ZM16 17H8V15H16V17ZM13 9H8V7H13V9Z" fill="white"/>
                    </svg>
                </div>
                <p>拖放正面PDF文件到这里<br>或点击选择文件</p>
                <input type="file" id="frontFile" class="file-input" accept=".pdf">
            </div>
            <p>正面文件顺序: 1, 3, 5, 7, 9, ...</p>
            
            <div class="drop-area" id="dropBack" style="margin-top: 30px;">
                <div>
                    <svg width="50" height="50" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M14 2H6C4.9 2 4.01 2.9 4.01 4L4 20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#2ecc71"/>
                        <path d="M14 2V8H20" fill="#27ae60"/>
                        <path d="M16 13H8V11H16V13ZM16 17H8V15H16V17ZM13 9H8V7H13V9Z" fill="white"/>
                    </svg>
                </div>
                <p>拖放反面PDF文件到这里<br>或点击选择文件</p>
                <input type="file" id="backFile" class="file-input" accept=".pdf">
            </div>
            <p>反面文件顺序: 10, 8, 6, 4, 2, ...</p>
            
            <button id="mergeBtn" class="btn btn-merge" disabled>合并PDF文件</button>
        </div>
        
        <div class="result-section">
            <h2>合并结果</h2>
            
            <div class="visualization">
                <h3>合并过程可视化</h3>
                <p>正面文件页码顺序:</p>
                <div class="page-sequence" id="frontSequence">
                    <div class="page page-front">1</div>
                    <div class="page page-front">3</div>
                    <div class="page page-front">5</div>
                    <div class="page page-front">7</div>
                    <div class="page page-front">9</div>
                </div>
                
                <p>反面文件页码顺序:</p>
                <div class="page-sequence" id="backSequence">
                    <div class="page page-back">10</div>
                    <div class="page page-back">8</div>
                    <div class="page page-back">6</div>
                    <div class="page page-back">4</div>
                    <div class="page page-back">2</div>
                </div>
                
                <p>合并后页码顺序:</p>
                <div class="page-sequence" id="mergedSequence">
                    <div class="page page-merged">1</div>
                    <div class="page page-merged">2</div>
                    <div class="page page-merged">3</div>
                    <div class="page page-merged">4</div>
                    <div class="page page-merged">5</div>
                    <div class="page page-merged">6</div>
                    <div class="page page-merged">7</div>
                    <div class="page page-merged">8</div>
                    <div class="page page-merged">9</div>
                    <div class="page page-merged">10</div>
                </div>
            </div>
            
            <div id="statusMsg" class="status">
                请上传正面和反面的PDF文件
            </div>
            
            <button id="downloadBtn" class="btn" disabled style="width: 100%; margin-top: 20px;">
                下载合并后的PDF文件
            </button>
        </div>
    </div>
    
    <footer>
        <p>© 2023 PDF扫描件合并工具 | 解决正面顺序、反面逆序的PDF合并问题</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const frontFileInput = document.getElementById('frontFile');
            const backFileInput = document.getElementById('backFile');
            const dropFront = document.getElementById('dropFront');
            const dropBack = document.getElementById('dropBack');
            const mergeBtn = document.getElementById('mergeBtn');
            const downloadBtn = document.getElementById('downloadBtn');
            const statusMsg = document.getElementById('statusMsg');
            
            let frontPdfFile = null;
            let backPdfFile = null;
            let mergedPdfBytes = null;
            
            // 设置拖放事件处理
            setupDropZone(dropFront, frontFileInput, (file) => {
                frontPdfFile = file;
                updateStatus();
            });
            
            setupDropZone(dropBack, backFileInput, (file) => {
                backPdfFile = file;
                updateStatus();
            });
            
            // 点击拖放区域触发文件选择
            dropFront.addEventListener('click', () => {
                frontFileInput.click();
            });
            
            dropBack.addEventListener('click', () => {
                backFileInput.click();
            });
            
            // 文件选择变化事件
            frontFileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    frontPdfFile = e.target.files[0];
                    updateStatus();
                }
            });
            
            backFileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    backPdfFile = e.target.files[0];
                    updateStatus();
                }
            });
            
            // 更新状态
            function updateStatus() {
                if (frontPdfFile && backPdfFile) {
                    mergeBtn.disabled = false;
                    statusMsg.textContent = '已选择两个PDF文件，点击"合并PDF文件"按钮开始合并';
                    statusMsg.className = 'status success';
                } else if (frontPdfFile) {
                    statusMsg.textContent = '已选择正面PDF文件，请选择反面PDF文件';
                    statusMsg.className = 'status';
                } else if (backPdfFile) {
                    statusMsg.textContent = '已选择反面PDF文件，请选择正面PDF文件';
                    statusMsg.className = 'status';
                } else {
                    statusMsg.textContent = '请上传正面和反面的PDF文件';
                    statusMsg.className = 'status';
                }
            }
            
            // 合并按钮点击事件
            mergeBtn.addEventListener('click', async () => {
                if (!frontPdfFile || !backPdfFile) {
                    statusMsg.textContent = '请先选择两个PDF文件';
                    statusMsg.className = 'status error';
                    return;
                }
                
                statusMsg.textContent = '正在处理PDF文件，请稍候...';
                statusMsg.className = 'status';
                mergeBtn.disabled = true;
                
                try {
                    // 读取PDF文件
                    const frontArrayBuffer = await readFileAsArrayBuffer(frontPdfFile);
                    const backArrayBuffer = await readFileAsArrayBuffer(backPdfFile);
                    
                    // 加载PDF文档
                    const { PDFDocument } = PDFLib;
                    const frontPdfDoc = await PDFDocument.load(frontArrayBuffer);
                    const backPdfDoc = await PDFDocument.load(backArrayBuffer);
                    
                    // 创建新的PDF文档
                    const mergedPdfDoc = await PDFDocument.create();
                    
                    // 获取页面
                    const frontPages = frontPdfDoc.getPages();
                    const backPages = backPdfDoc.getPages();
                    
                    // 检查页面数量是否匹配
                    if (frontPages.length !== backPages.length) {
                        statusMsg.textContent = `错误: 两个PDF文件的页数不匹配 (正面: ${frontPages.length}页, 反面: ${backPages.length}页)`;
                        statusMsg.className = 'status error';
                        mergeBtn.disabled = false;
                        return;
                    }
                    
                    // 交叉合并页面 (正面顺序，反面逆序)
                    for (let i = 0; i < frontPages.length; i++) {
                        // 添加正面页面 (顺序)
                        const [frontPage] = await mergedPdfDoc.copyPages(frontPdfDoc, [i]);
                        mergedPdfDoc.addPage(frontPage);
                        
                        // 添加反面页面 (逆序)
                        const backIndex = backPages.length - 1 - i;
                        const [backPage] = await mergedPdfDoc.copyPages(backPdfDoc, [backIndex]);
                        mergedPdfDoc.addPage(backPage);
                    }
                    
                    // 保存合并后的PDF
                    mergedPdfBytes = await mergedPdfDoc.save();
                    
                    statusMsg.textContent = `PDF合并成功! 总共 ${frontPages.length * 2} 页。点击下方按钮下载合并后的文件。`;
                    statusMsg.className = 'status success';
                    downloadBtn.disabled = false;
                    
                } catch (error) {
                    console.error('PDF处理错误:', error);
                    statusMsg.textContent = '处理PDF时发生错误: ' + error.message;
                    statusMsg.className = 'status error';
                    mergeBtn.disabled = false;
                }
            });
            
            // 下载按钮点击事件
            downloadBtn.addEventListener('click', () => {
                if (mergedPdfBytes) {
                    const fileName = `合并后的PDF_${new Date().toISOString().slice(0, 10)}.pdf`;
                    download(mergedPdfBytes, fileName, 'application/pdf');
                }
            });
            
            // 工具函数：读取文件为ArrayBuffer
            function readFileAsArrayBuffer(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = reject;
                    reader.readAsArrayBuffer(file);
                });
            }
            
            // 工具函数：设置拖放区域
            function setupDropZone(dropZone, fileInput, callback) {
                dropZone.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    dropZone.style.backgroundColor = '#e1f0fa';
                });
                
                dropZone.addEventListener('dragleave', (e) => {
                    e.preventDefault();
                    dropZone.style.backgroundColor = '#f8fafc';
                });
                
                dropZone.addEventListener('drop', (e) => {
                    e.preventDefault();
                    dropZone.style.backgroundColor = '#f8fafc';
                    
                    if (e.dataTransfer.files.length > 0) {
                        const file = e.dataTransfer.files[0];
                        if (file.type === 'application/pdf') {
                            callback(file);
                        } else {
                            statusMsg.textContent = '请上传PDF文件';
                            statusMsg.className = 'status error';
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>